package com.juqimiao.outposts.spring.oauth2.mobile.token;

import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.SpringSecurityCoreVersion;

import java.util.Collection;
import java.util.List;

public class UserMobileCodeAuthenticationToken extends AbstractAuthenticationToken {
    private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;

    private Object principal;

    private Object credentials;

    /**
     * 通过此构造器创建一个
     * <code>UserMobileCodeAuthenticationToken</code>, as the {@link #isAuthenticated()}
     * 作为 {@link #isAuthenticated()} 它将返回 <code>false</code>.
     */
    public UserMobileCodeAuthenticationToken(Object principal, Object credentials) {
        super(null);
        this.principal = principal;
        this.credentials = credentials;
        setAuthenticated(false);
    }

    /**
     * 通过此构造器使用<code>AuthenticationManager</code> 或者 <code>AuthenticationProvider</code> 的实现类
     * <code>UserMobileCodeAuthenticationToken</code>, as the {@link #isAuthenticated()}
     * 作为 {@link #isAuthenticated()} 它将返回 <code>false</code>.
     *
     * @param principal   一个用户标识对象.
     * @param credentials 一个用户安全凭证对象(password or mobile code).
     * @param authorities {@link List <  GrantedAuthority  >}
     */
    public UserMobileCodeAuthenticationToken(Object principal, Object credentials,
                                             Collection<? extends GrantedAuthority> authorities) {
        super(authorities);
        this.principal = principal;
        this.credentials = credentials;
        // must use super, as we override
        super.setAuthenticated(true);
    }

    /**
     * 创建一个提供 Authority的集合的token.
     *
     * @param authorities 在principal包含<tt>GrantedAuthority</tt>的集合
     */
    public UserMobileCodeAuthenticationToken(Collection<? extends GrantedAuthority> authorities) {
        super(authorities);
    }

    /**
     * 获取一个用户凭证.
     *
     * @return 用户凭证.
     */
    @Override
    public Object getCredentials() {
        return this.credentials;
    }

    /**
     * 设置一个用户标识.
     *
     * @return 用户标识.
     */
    @Override
    public Object getPrincipal() {
        return this.principal;
    }

    /**
     * 设置一个授权标识.
     *
     * @param isAuthenticated 授权标识.
     * @throws IllegalArgumentException {@link IllegalArgumentException}
     */
    @Override
    public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
        if (isAuthenticated) {
            throw new IllegalArgumentException(
                    "Cannot set this token to trusted - use constructor which takes a GrantedAuthority list instead");
        }

        super.setAuthenticated(false);
    }

    /**
     * 抹去用户凭证
     */
    @Override
    public void eraseCredentials() {
        super.eraseCredentials();
        credentials = null;
    }
}
